import { url } from "./config.js"
import { LazyLoad } from "../../static/javascripts/Utils.js";
import { cookie } from "../../static/javascripts/cookie.js"

$(document).ready(function () {
    //获取页面数据
    async function getGoodsData() {
        let res = await axios(url + "/activeData.json")
        let data = res.data;
        //渲染数据
        data.forEach(item => {
            item.goodslist.forEach(_item => {
                _item = Object.assign(_item, { cont: 1 })
            })
        })
        render(data);
    }
    function render(data) {
        let htmlStr = "";
        let stairs = [];
        data.forEach((item, index) => {
            let liStr = "";
            item.goodslist.forEach((_item, _index) => {
                liStr += `
               <li class="proItem"  goodsId ="${_item.content.goodsId}"">
                    <dl class="goodsBD">
                        <dt class="goodsImg">
                            <a href=""  goodsId ="${_item.content.goodsId}""> <img data-src="${_item.content.imageUrl}" alt=""></a>
                        </dt>
                        <dd class="goodsInfo">
                            <div class="goodstitle">
                                <p class="title"  goodsId ="${_item.content.goodsId}"">${_item.content.title}</p>
                            </div>
                            <div class="priceInfo">
                                <dl class="price">
                                    <dt class="nowPrice"><span class="symbol">$</span><span class="priceText">${_item.content.priceInfo.normalPrice}</span></dt>
                                    <dd class="oldPrice"><span class="symbol">$</span><span class="priceText"><del>${_item.content.priceInfo.marketPrice}</del></span></dd>
                                </dl>
                                <div class="shopCar" goodsId ="${_item.content.goodsId}" classindex="${index}" itemindex="${_index}">
                                    <i class="iconfont icon-gouwuche"></i>
                                </div>
                            </div>
                        </dd>
                    </dl>
                </li>`;
            })
            htmlStr += `
            <div class="item">
                <div class="itemTitle">${item.goodslist[0].content.categoryName}</div>
                    <ul class="goodsList">                                                                                                                                                      
                        ${liStr}
                    </ul>
            </div>
           `;
            stairs.push(item.goodslist[0].content.categoryName)
        });
        $(".goodsContainer").append(htmlStr);
        let stairsStr = "";
        stairs.forEach((item, index) => {
            stairsStr += `
            <li stairs_index=${index}>${item}</li>
            `
        });
        stairsStr += `<li stairs_index="top"><i class="iconfont icon-top"></i></li>`
        $(".stairs").append(stairsStr);
        //楼梯效果
        $(".stairs").find("li").on("click", function () {
            let index = $(this).attr("stairs_index");
            let nav_height = $("nav").innerHeight();
            let pre_heigth = $(".hotBrand").innerHeight() + $(".active_bigImg").innerHeight();
            let item_height = $(".goodsContainer ").find(".item").eq(0).innerHeight();
            if (index === "top") {
                $("html,body").stop().animate({ scrollTop: "10" });
            }
            else {
                $("html,body").stop().animate({ scrollTop: ((nav_height + pre_heigth) + index * item_height) });
            }
        })
        //吸顶效果
        let time;
        let offset = $(".goodsContainer").offset();
        let left_position = offset.left - 200;
        $(window).on("resize", function () {
            offset = $(".goodsContainer").offset()
            left_position = offset.left - 200;
            $(".stairs").css({
                "left": left_position + "px"
            })
        })

        $(window).scroll(function () {
            clearTimeout(time)
            time = setTimeout(function () {
                //楼梯吸顶效果
                if (scrollY >= offset.top - 100) {
                    $(".stairs").css({
                        "display": "block",
                        "position": "fixed",
                        "top": "100px",
                        "left": left_position + "px"
                    })
                } else {
                    time = setTimeout(function () {
                        $(".stairs").css({
                            "display": "none",
                        })
                    }, 0);
                }
            }, 0)
        });
        //购物车

        let shopCarList = JSON.parse(localStorage.getItem("shopCat"));
        shopCarList === null ? [] : shopCarList;
        let goods = {};
        let _index = 0;
        let clickcont = 1;
        let num = 0;
        $(".shopCar").on("click", function () {
            if (checkLogin()) {
                rotateI($(this), clickcont);
                let goodsId = $(this).attr("goodsId");
                let classindex = $(this).attr("classindex");
                let itemindex = $(this).attr("itemindex");
                goods = Object.assign(data[classindex].goodslist[itemindex], { Id: goodsId })
                // console.log(goods);
                
                if (hasRepeat(goods)) {
                    // console.log("有重复");
                    num = shopCarList[_index].cont;
                    num ++;
                    num = num >= 6 ? 6 : num;
                    console.log("aa",num);
                    shopCarList[_index].cont = num;
                    if(num ===6){
                        alert("已超过最大购买件数!同种商品最多购买6件")
                    }
                    console.warn(shopCarList[_index].cont)
                }
                if (!hasRepeat(goods)) {
                    // console.log("没有重复");
                    shopCarList.push(goods)
                    num = 1;
                }
                localStorage.setItem("shopCat", JSON.stringify(shopCarList));
                clickcont++
            }

        });
        function checkLogin() {
            let TOKEN = cookie("TOKEN");
            if (TOKEN === null || TOKEN === undefined || TOKEN === "") {
                console.log(11);
                $("#login").trigger("click");
            } else {
                return true;
            }
        }
        function hasRepeat(goods) {
            // console.log(shopCarList,goods);
            let flag = false
            for (let i = 0; i < shopCarList.length; i++) {
                // console.log(shopCarList[i].Id,goods.Id);
                if (shopCarList[i].Id === goods.Id) {
                    _index = i
                    flag = true
                    return true;
                }
            }
            if (flag == false)
                return false;
        }

        function rotateI(ele, clickcont) {
            ele.find("i").rotate({ animateTo: 360 * clickcont, duration: 500 });
        }
        $("a").on("click", e => {
            e.preventDefault();
        })
        $(".proItem").find(".goodsImg").on("click", function () {
            let id = $(this).parents("li.proItem").attr("goodsid")
            console.log(id);
            location.href = `../../dist/product.html#id=${id}`;
        })
        new LazyLoad(".goodsImg img")
    }
    getGoodsData();
});